'use strict';
const db = uniCloud.database()
const {
	getAccessToken
} = require('security')
// const template_id = 'jKBlYPmn5e9Fb-2Kt_FrplnxcN53XOHOOF28a9k9PXE'
exports.main = async (event, context) => {

	let userarr = await getUserOpenid()
	for (let i = 0; i < userarr.length; i++) {
		let result = await getMessageList(userarr[i])
		let messlist = result.data
		if (Array.isArray(messlist)) {
			for (let j = 0; j < messlist.length; j++) {
				uniCloud.logger.info(messlist[j])
				let result = await sendMessage(userarr[i].openid, [messlist[j].title, messlist[j].info, messlist[j]._id],
					messlist[j].type)
				uniCloud.logger.info('用户' + userarr[i].username)
				uniCloud.logger.info(result)
				// if (result.res.data.errcode === 0) {
				// 	upIsSend(userarr[i].openid, messlist[j]._id, 2)
				// } else {
				// 	upIsSend(userarr[i].openid, messlist[j]._id, 3)
				// }
			}
		}
	}

	//返回数据给客户端
	return '已调用发送模板'
};
/**
 * 获取用户openid与名称数组 
 */
function getUserOpenid() {
	return new Promise(async resolve => {
		const collection = db.collection('user-info')
		let userList = await collection.get()
		let arr = []
		userList.data.forEach(e => {
			let item = {
				openid: e.openid,
				username: e.nickName
			}
			arr.push(item)

		})
		resolve(arr)
	})

}
// 获取某个用户的消息列表
function getMessageList(userinfo) {
	const collection = db.collection('message-list')
	let time = new Date(Date.now() + (8 * 60 * 60 * 1000))
	let year = Number(time.getFullYear()) < 10 ? `0${ Number(time.getFullYear())}` : time.getFullYear()
	let month = Number(time.getMonth() + 1) < 10 ? `0${ time.getMonth() + 1}` : time.getMonth() + 1
	let day = Number(time.getDate()) < 10 ? `0${time.getDate()}` : time.getDate()
	let hours = Number(time.getHours()) < 10 ? `0${ time.getHours()}` : time.getHours()
	return new Promise(async resolve => {
		let result = await collection.where({
			openid: userinfo.openid,
			year: year.toString(),
			month: month.toString(),
			day: day.toString(),
			hour: hours.toString(),
			issend: true,
			sendsuccess: 1
		}).get()
		resolve(result)
	})
}
// 发送成功地把信息改为不需要发送
// sendsuccess状态值  1:待发送 2:发送成功 3：发送失败
function upIsSend(openid, messageid, type) {
	const collection = db.collection('message-list')
	collection.where({
		openid: openid,
		_id: messageid
	}).update({
		sendsuccess: type
	})
}

// 发送模板消息
async function sendMessage(touser, arr, type) {
	let time = new Date(Date.now() + (8 * 60 * 60 * 1000))
	uniCloud.logger.info(type)
	if (type == 'wx') {
		let access_token = await getAccessToken('wx')
		let data = {
			"touser": touser,
			"data": {
				"name1": {
					"value": '你要做的事情到时间了哦~'
				},
				"date2": {
					"value": time.toLocaleDateString()
				},
				"thing3": {
					"value": arr[0]
				},
				"thing9": {
					"value": arr[1]
				}
			},
			"template_id": 'jKBlYPmn5e9Fb-2Kt_FrplnxcN53XOHOOF28a9k9PXE',
			"page": `/pages/messageDetile/messageDetile?id=${arr[2]}`,
			"miniprogram_state": "formal"
		}
		return uniCloud.httpclient.request(
			`https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=${access_token}`, {
				method: 'POST',
				data: JSON.stringify(data),
				dataType: 'json'
			})
	}
	if (type == 'qq') {
		let access_token = await getAccessToken('qq')
		let qdata = {
			"touser": touser,
			"data": {
				"keyword1": {
					"value": '你要做的事情到时间了哦~'
				},
				"keyword2": {
					"value": time.toLocaleDateString()
				},
				"keyword3": {
					"value": arr[0]
				},
				"keyword3": {
					"value": arr[1]
				},
			},
			"template_id":'d1938f41003ea26e8319c997da6b89c1',
			"page": `/pages/messageDetile/messageDetile?id=${arr[2]}`,
		}
		uniCloud.logger.info(access_token)
		return await uniCloud.httpclient.request(
			`https://api.q.qq.com/api/json/subscribe/SendSubscriptionMessage?access_token=${access_token}`, {
				method: 'POST',
				dataAsQueryString: false,
				data: JSON.stringify(qdata),
				headers: { "content-type": "application/json" },
				dataType: 'json'
			})
	}

}
